package other.edan.pass.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CustomConfigService;
import org.apache.commons.lang.StringUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

public class K3CloudUtils {


    public static final Logger logger = LoggerFactory.getLogger();

    public static String acctID;
    public static String lcid;
    public static String username;
    public static String password;
    public static String url;
    public static final String AUTH = "RP";  //组织机构

    public static final String filterString = "FSaleOrgId != 391803 AND FSaleOrgId <> 1194958 AND FDocumentStatus = 'C'";   //查询ERP数据过滤条件（公共查询条件）

//    public static final String ACCOUNT_CONFIG = "ErpConfigTest";  //ERP测试环境配置
    public static final String ACCOUNT_CONFIG = "ErpConfig";    //ERP正式环境配置

    public static final String BD_MATERIAL = "BD_MATERIAL";   //金蝶对象标识-物料
    public static final String SAL_SaleOrder = "SAL_SaleOrder";   //金蝶对象标识-销售订单
    public static final String SAL_XORDER = "SAL_XORDER";   //金蝶对象标识-销售订单变更单fo
    public static final String SAL_DELIVERYNOTICE = "SAL_DELIVERYNOTICE";   //金蝶对象标识-发货通知
    public static final String SAL_OUTSTOCK = "SAL_OUTSTOCK";   //金蝶对象标识-销售出库单
    public static final String AR_receivable = "AR_receivable";   //金蝶对象标识-应收单
    public static final String AR_RECEIVEBILL = "AR_RECEIVEBILL";   //金蝶对象标识-收款单
    public static final String SAL_RETURNSTOCK = "SAL_RETURNSTOCK";   //金蝶对象标识-销售退货
    public static final String AR_Match = "AR_Match";   //金蝶对象标识-应收核销单
    public static final String BOS_OperateLog = "BOS_OperateLog";   //金蝶对象标识-上级操作日志
    public static final String SAL_BATCHADJUSTPRICE = "SAL_BATCHADJUSTPRICE";   //金蝶对象标识-批量调价单

    public static final int Audit = 1; // 审核
    public static final int UN_Audit = 2; // 反审核

    static {
        // 获取对象实例
        CustomConfigService instance = CustomConfigService.instance();
        // 获取配置集,返回此配置集中的所有配置项
        try {
            Map<String, String> configSet = instance.getConfigSet(ACCOUNT_CONFIG);
            if (configSet != null) {
                String erpUrl = configSet.get("erpUrl");
                url = StringUtils.isBlank(erpUrl) ? url : erpUrl;
            }else {
                Properties params = new Properties();
                InputStream inputStream = K3CloudUtils.class.getClassLoader().getResourceAsStream("oauthConfig.properties");
                try {
                    params.load(new InputStreamReader(inputStream, "UTF-8"));
//                    params.load(inputStream);
                    acctID = params.get("erpAcctID").toString();
                    lcid = params.get("erpLcId").toString();
                    username = params.get("erpUserName").toString();
                    password = params.get("erpPassword").toString();
                    url = params.get("erpApiUrl").toString();
                }catch (Exception e){
                    logger.error("loader conf error:" + e);
                }
            }
        } catch (CustomConfigException e) {
            e.printStackTrace();
        }

    }

    public static String getUrl(String path) throws CustomConfigException {
        // 获取对象实例
        CustomConfigService instance = CustomConfigService.instance();
        // 获取配置集,返回此配置集中的所有配置项
        Map<String, String> configSet = instance.getConfigSet(ACCOUNT_CONFIG);
        if (configSet == null) {
            return url + path;
        }

        logger.info("自定义配置金蝶访问路径：" + JSONObject.toJSONString(configSet));
        String erpUrl = configSet.get("erpUrl");
        url = StringUtils.isBlank(erpUrl) ? url : erpUrl;
        return url + path;

    }

    // 登录验证用户接口
    public static final String ValidateUser_URL = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
    // 批量查询数据
    public static final String ExecuteBillQuery_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc";
    // 批量保存数据
    public static final String BatchSave_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc";
    //保存单条数据接口
    public static final String Save_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc";
    //批量提交审批
    public static final String Submit_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc";
    //查询单条数据
    public static final String Query_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc";
    //批量删除数据
    public static final String Delete_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc";
    //批量反审核
    public static final String UnAudit_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc";
    //变更单创建新接口
    public static final String SaleOrder_RUL = "Kingdee.K3.SCM.WebApi.ServicesStub.SaveXSaleOrderWebApi.SaveXSaleOrder.common.kdsvc";

    // erp撤销提交接口
    public static final String Call_RUL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAssign.common.kdsvc";

    //批量审核
    public static final String Audit_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc";

    //分配
    public static final String Allocate_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate.common.kdsvc";

    //取消分配
    public static final String CancelAllocate_URL = "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAllocate.common.kdsvc";


    /**
     * 验证用户登录，只有登录后才能调用金蝶其他接口
     *
     * @throws Exception
     */
    public static String validateUser() throws Exception {
        JSONObject json = getUser();
        String sessionId = json.getString("KDSVCSessionId");
        return sessionId;
    }

    /**
     * 获取用户token
     *
     * @return
     * @throws Exception
     */
    public static String getUserToken() throws Exception {
        JSONObject json = getUser();
        Map map = (Map) json.getJSONObject("Context");
        String K3cloudToken = map.get("UserToken").toString();
        return K3cloudToken;

    }

    public static JSONObject getUser() throws Exception {
        Map<String, String> customConfigSet = getCustomConfigSet(ACCOUNT_CONFIG);
        logger.info("自定义配置信息：" + JSONObject.toJSONString(customConfigSet));
        if (customConfigSet != null) {
            username = customConfigSet.get("username") == null ? username : customConfigSet.get("username");
            password = customConfigSet.get("password") == null ? password : customConfigSet.get("password");
            acctID = customConfigSet.get("acctID") == null ? acctID : customConfigSet.get("acctID");
            lcid = customConfigSet.get("lcid") == null ? lcid : customConfigSet.get("lcid");
        }


        JSONObject param = new JSONObject(true);
        param.put("acctID", acctID);
        param.put("lcid", lcid);
        param.put("username", username);
        param.put("password", password);

        CommonData data = new CommonData();
        data.setCallString(getUrl(ValidateUser_URL));
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject json = JSONObject.parseObject(respStr.getResult());
        return json;
    }


    /**
     * 批量保存单据
     *
     * @throws Exception
     */
    public static JSONObject batchSave(JSONObject param) throws Exception {
        logger.debug("金蝶批量保存单据接口【BatchSave_URL】调用参数：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(BatchSave_URL)); //金蝶批量保存客户的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("金蝶批量保存单据接口【BatchSave_URL】调用结果：" + result.toJSONString());
        return result.getJSONObject("Result");
    }

    /**
     * 批量查询单据
     *
     * @throws Exception
     */
    public static JSONArray batchQuery(JSONObject param) throws Exception {
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser());
        data.setCallString(getUrl(ExecuteBillQuery_URL));
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        logger.debug("金蝶批量查询单据接口【ExecuteBillQuery_URL】调用参数：" + param);
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONArray result = JSONArray.parseArray(respStr.getResult());
        // logger.info("batchQuery result:"+result.toJSONString());
        logger.debug("金蝶批量查询单据接口【ExecuteBillQuery_URL】调用结果：" + result.toJSONString());

        return result;
    }

    /**
     * 批量提交单据
     *
     * @param: @param param
     * @param: @return
     * @param: @throws Exception
     * @return: JSONObject
     * @date: 上午12:56:39
     */
    public static JSONObject batchSubmit(JSONObject param) throws Exception {
        logger.debug("金蝶批量提交单据接口【Submit_URL】调用参数：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Submit_URL)); //金蝶批量提交客户的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("金蝶批量提交单据接口【Submit_URL】调用结果：" + result.toJSONString());
        return result.getJSONObject("Result");
    }

    /**
     * 批量审批单据
     *
     * @param: @param param
     * @param: @return
     * @param: @throws Exception
     * @return: JSONObject
     * @date: 上午12:56:39
     */
    public static JSONObject batchApproval(JSONObject param) throws Exception {
        logger.debug("金蝶批量提交单据接口【Audit_URL】调用参数：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Audit_URL));
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("金蝶批量提交单据接口【Audit_URL】调用结果：" + result.toJSONString());
        return result.getJSONObject("Result");
    }

    /**
     * 单条数据查询
     *
     * @param: @param param
     * @param: @return
     * @param: @throws Exception
     * @return: JSONObject
     * @date: 上午11:23:28
     */
    public static JSONObject query(JSONObject param) throws Exception {
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Query_URL)); //金蝶查询单条数据的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("单条数据查询接口【Query_URL】调用结果：" + result.getJSONObject("Result").toJSONString());
        return result.getJSONObject("Result");
    }

    /**
     * 存储单条数据
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject save(JSONObject param) throws Exception {
        logger.debug("单条数据【Save_URL】调用json：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Save_URL)); //金蝶查询单条数据的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        return result.getJSONObject("Result");
    }


    /**
     * 批量删除
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject delete(JSONObject param) throws Exception {
        logger.debug("单条数据【Delete_URL】调用json：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Delete_URL)); //金蝶查询单条数据的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("单条数据【Delete_URL】调用结果：" + result.getJSONObject("Result").toJSONString());
        return result.getJSONObject("Result");
    }


    /**
     * 金蝶反审核
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject unAudit(JSONObject param) throws Exception {
        logger.debug("单条数据【UnAudit_URL】调用json：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(UnAudit_URL)); //金蝶反审核
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("单条数据【UnAudit_URL】调用结果：" + result.getJSONObject("Result").toJSONString());
        return result.getJSONObject("Result");
    }


    /**
     * 金蝶撤销接口
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject call(JSONObject param) throws Exception {
        logger.debug("单条数据【call】调用json：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        logger.info("访问地址：" + Call_RUL);
        data.setCallString(getUrl(Call_RUL)); //金蝶撤销接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.info("撤销结果：" + result);
        logger.debug("单条数据【call】调用结果：" + result.getJSONObject("Result").toJSONString());
        return result.getJSONObject("Result");
    }

    public static Boolean submitInfo(String number, String formId) throws Exception {
        Boolean success = false;
        // 封装参数
        JSONObject submitParam = new JSONObject(true);
        submitParam.put("formid", formId);
        JSONObject submitData = new JSONObject(true);
        submitData.put("Numbers", number);
        submitParam.put("data", submitData);
        // 调用金蝶提交客户接口
        JSONObject submitResult = K3CloudUtils.batchSubmit(submitParam);
        JSONObject successEntity = submitResult.getJSONObject("ResponseStatus");
        if (successEntity.getJSONArray("SuccessEntitys").size() > 0) {
            success = true;
            logger.debug("客户提交成功：" + submitResult.toJSONString());
        } else {
            logger.debug("客户提交失败：" + submitResult.toJSONString());
        }

        return success;
    }


    /**
     * 创建变更单
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject createOrderChange(JSONObject param) throws Exception {
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(SaleOrder_RUL)); //金蝶查询单条数据的API接口
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        return result;
    }

    /**
     * 提交ERP变更单审批
     *
     * @param fid 变更单erpid
     * @return
     */
    public static boolean submitApproval(String fid,String object) throws Exception {
        JSONObject data = new JSONObject(true);  //自动开启过滤中为null的值数据
        JSONObject submitData = new JSONObject(true);
        data.put("formid", object); // 设置表单对象
        submitData.put("CreateOrgId", getErpFNumber(K3CloudUtils.AUTH)); // 创建者组织内码
        submitData.put("Ids", fid);
        data.put("data", submitData);
        JSONObject submitResult = batchSubmit(data);

        JSONObject successEntity = submitResult.getJSONObject("ResponseStatus");
        //判断调用是否成功
        if (!successEntity.getBoolean("IsSuccess")) {
            Map errorsMap = (Map) successEntity.getJSONArray("Errors").get(0);
            logger.debug("提交审批失败：" + errorsMap.get("Message"));
            return false;
        }
        logger.info("提交审批成功");
        return true;

    }

    /**
     * 分配
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject allocate(JSONObject param) throws Exception {
        logger.debug("金蝶分配接口【Allocate_URL】调用参数：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(Allocate_URL));
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("金蝶分配接口【Allocate_URL】调用结果：" + result.toJSONString());
        return result.getJSONObject("Result");
    }

    /**
     * 取消分配
     * @param param
     * @return
     * @throws Exception
     */
    public static JSONObject cancelAllocate(JSONObject param) throws Exception {
        logger.debug("金蝶取消分配接口【Allocate_URL】调用参数：" + param);
        CommonData data = new CommonData();
        data.addHeader("kdservice-sessionid", validateUser()); //通过账号密码获取sessionId
        data.setCallString(getUrl(CancelAllocate_URL));
        data.setCall_type("POST");
        data.setBody(param.toJSONString());
        HttpResult respStr = CommonHttpClient.instance().execute(data);
        JSONObject result = JSONObject.parseObject(respStr.getResult());
        logger.debug("金蝶取消分配接口【Allocate_URL】调用结果：" + result.toJSONString());
        return result.getJSONObject("Result");
    }

    public static JSONObject getErpFNumber(Object data) {
        JSONObject FSALDEPTID = new JSONObject();
        FSALDEPTID.put("FNumber", data);
        return FSALDEPTID;
    }

    /**
     * 字段集合去重
     *
     * @param list
     * @return
     */
    public static List<String> removeObject(List<String> list) {
        //先进行字段去重
        ArrayList reList = new ArrayList();

        for (Iterator t = list.iterator(); t.hasNext(); ) {
            Object c = t.next();
            //此处contains调用了被重写的equals方法。
            if (!(reList.contains(c))) {
                reList.add(c);
            }
        }
        System.out.println(reList.toString());
        return reList;
    }

    /**功能描述：获取配置集
     * @param:configKey：配置集名称
     * @return:该配置集的所有配置项信息
     */
    public static Map < String,String > getCustomConfigSet(String configKey) throws CustomConfigException {
        // 获取对象实例
        CustomConfigService instance = CustomConfigService.instance();

        // 获取配置集,返回此配置集中的所有配置项
        Map <String,String> configSet = instance.getConfigSet(configKey);

        return configSet;
    }

    /**
     * 获取配置集中的一个配置项；itemKey 为  配置集找那个创建的配置项的key
     */
    public String getCustomConfigItem(String configKey, String itemKey) throws CustomConfigException {
        String itemValue = getCustomConfigSet(configKey).get(itemKey);
        return itemValue;
    }

    /**
     * ERP时间类型转换
     * @param strTime
     * @return
     */
    public static Long getErpTime(String strTime){
        try {
            if (StringUtils.isBlank(strTime)){
                return null;
            }
            if (strTime.contains("T")){
                return DateTools.stringToLong(strTime.replace("T", " "), getTimeStrFormat(strTime));
            }else if (strTime.contains(" ")){
                return DateTools.stringToLong(strTime, getTimeStrFormat(strTime));
            }else {
                return DateTools.dateStrToLong(strTime);
            }
        }catch (Exception e){
            LoggerUtils.info("时间转换异常, error:", e);
            throw e;
        }
    }

    private static String getTimeStrFormat(String strTime) {
        StringBuilder dateFormat = new StringBuilder("yyyy-MM-dd HH:mm:ss");
        if (strTime.contains(".")) {
            String[] split = strTime.split("\\.");
            int length = split[1].length();
            dateFormat.append(".");
            for (int i = 0; i < length; i++) {
                dateFormat.append("S");
            }
        }
        return dateFormat.toString();
    }

    /**
     * ERP时间转换为时间戳
     * @param time
     * @return
     */
    public static Long getDateLong(String time){
        if (StringUtils.isBlank(time)){
            return null;
        }
        return DateTools.stringToLong(time.replace("T", " "), DateTools.getTimeStrFormat(time));
    }


//    public static void main(String[] args) throws Exception {
//        System.out.println(validateUser());
//    }


}
